from jili.core.printlog import print
from jili.data.db import getdb_client,insert_one
dbs={}
"""
自持连接保存，要求配置为py config;mongo_ip,mongo_auth,mongo_db
新增
更新
额外任务处理；还是主线程  当前主线程处理
"""
def get_db(dbname,config=None):
    if config:
        if isinstance(config, dict):
            db = getdb_client(dbname=dbname, ip=config["mongo_ip"], auth=config["mongo_auth"])
        else:
            db = getdb_client(dbname=dbname, ip=config.mongo_ip, auth=config.mongo_auth)
    else:
        db = getdb_client(dbname=dbname)
    return db
def mongo_save(dbname,cuname,data,config=None,isupdate=False,id=None):
    global dbs
    if data:
        key=dbname+"."+cuname
        if key in dbs.keys():
            cu=dbs[key]
        else:
            db=get_db(dbname,config)
            cu = db[cuname]
            dbs[key]=cu
        try:
            if isupdate:
                if isinstance(data,list):
                    for i in data:
                        insert_one(cu, i, updteflag=True, id=id)
                else:
                    insert_one(cu, data,updteflag=True, id=id)
            else:
                if isinstance(data,list):
                    cu.insert_many(data)
                else:
                    insert_one(cu, data)
        except Exception as e:
            print("error","mongo_save", e)
            db = get_db(dbname, config)
            cu = db[cuname]
            dbs[key] = cu
            if isinstance(data,list):
                for i in data:
                    insert_one(cu, i,updteflag=isupdate,id=id)
            else:
                insert_one(cu, i,updteflag=isupdate,id=id)
